#! /bin/sh

if [[ ! -e /etc/openvpn/server/server.crt ]] || [[ ! -e /etc/openvpn/server/server.key ]] || [[ ! -e /etc/openvpn/server/ca.crt ]] || [[ ! -e /etc/openvpn/server/ca.key ]] || [[ ! -e /etc/openvpn/server/dh.pem ]] || [[ ! -e /etc/openvpn/server/crl.pem ]] || [[ ! -e /etc/openvpn/server/tc.key ]]
then
  chown -R root:root /etc/openvpn/server/easy-rsa/
  cd /etc/openvpn/server 
  rm -f *.pem *.key *.crt 
  cd easy-rsa/
  ./easyrsa --batch init-pki
  ./easyrsa --batch build-ca nopass
  ./easyrsa --batch --days=3650 build-server-full server nopass
  ./easyrsa --batch --days=3650 gen-crl
  cp -a pki/ca.crt pki/private/ca.key pki/issued/server.crt pki/private/server.key pki/crl.pem /etc/openvpn/server
  chown nobody:nogroup /etc/openvpn/server/crl.pem
  chmod o+x /etc/openvpn/server/
  openvpn --genkey secret /etc/openvpn/server/tc.key
  openssl dhparam -out dh.pem 2048
  mv dh.pem /etc/openvpn/server/dh.pem
fi

if [ ! -d /dev/net ]
then
  mkdir -p /dev/net
  mknod /dev/net/tun c 10 200
  chmod 600 /dev/net/tun
fi

iptables -t nat -A POSTROUTING -s 10.8.0.0/24 -o eth0 -j MASQUERADE
openvpn --daemon --cd /etc/openvpn/server/ --config /etc/openvpn/server/server.conf --status /etc/openvpn/server/status.log --status-version 2

cd /opt

./ovpnc
